package com.vbez.sommelier.rawinfo;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class RawInfoApp {
	private static List<RawItem> getItems(String startURL, int days) {
		WebPageReader reader = new WebPageReader();
		List<RawItem> items = reader.getItems(startURL, days);
		System.out.println("Total items: " + items.size());
		return items;
	}

	private static List<RawItem> getReviewItems(List<RawItem> items) {
		List<RawItem> reviewItems = new ArrayList<RawItem>();

		Map<Integer, Integer> commaMap = new HashMap<Integer, Integer>();
		/*
		 * for (RawItem item : items) { int count = 0; for(int i =0;
		 * i<item.subject.length(); i++) { if (item.subject.charAt(i) == ',') {
		 * count++; } } if (commaMap.containsKey(count)) { commaMap.put(count,
		 * commaMap.get(count)+1); } else { commaMap.put(count, 1); }
		 * 
		 * if (count < 4) { byte[] winData = null; try { winData =
		 * item.subject.getBytes("Cp866"); } catch (UnsupportedEncodingException
		 * e) { // TODO Auto-generated catch block e.printStackTrace(); }
		 * 
		 * System.out.println("item.subject[" + count + "]: " + new
		 * String(winData)); System.out.println(item.link); } }
		 * 
		 * for (Integer key : commaMap.keySet()) { System.out.println(key +
		 * "commas : " + commaMap.get(key) + " times"); }
		 */

		for (RawItem item : items) {
			int count = item.tags.size();
			if (count < 3) {
				System.out.println(count + " tags :" + item.link);
			}
		}

		return reviewItems;
	}

	public static void main(String[] args) {
		String startURL = args[0];
		int days = Integer.parseInt(args[1]);
		List<RawItem> items = getItems(startURL, days);
		storeItems(items);

		/*
		 * for (RawItem item : items) { try {
		 * System.out.println("item.dateTime: " + item.dateTime);
		 * System.out.println("item.link: " + item.link); byte[] winData =
		 * item.subject.getBytes("Cp866");
		 * 
		 * System.out.println("item.subject: " + new String(winData)); winData =
		 * item.description.getBytes("Cp866");
		 * System.out.println("item.description: " + new String(winData));
		 * System.out.println("item.pictureURL: " + item.pictureURL);
		 * System.out.println("item.nextDayLink: " + item.nextDayLink);
		 * 
		 * for (String tag : item.tags) { winData = tag.getBytes("Cp866");
		 * System.out.println("Tag: " + new String(winData)); } } catch
		 * (UnsupportedEncodingException e) { // TODO Auto-generated catch block
		 * e.printStackTrace(); } }
		 */

		//getReviewItems(items);
	}

	private static void storeItems(List<RawItem> items) {
		String driver = "org.apache.derby.jdbc.ClientDriver";
		String dbName = "sommelier_raw";
		String connectionURL = "jdbc:derby://localhost:1527/" + dbName
				+ ";create=false";
		Connection conn = null;
		PreparedStatement psInsert;

		try {
			Class.forName(driver);
			System.out.println(driver + " loaded. ");
		} catch (java.lang.ClassNotFoundException e) {
			System.err.print("ClassNotFoundException: ");
			System.err.println(e.getMessage());
			System.out
					.println("\n    >>> Please check your CLASSPATH variable   <<<\n");
		}

		try {
			conn = DriverManager.getConnection(connectionURL);
			System.out.println("Connected to database " + dbName);

			psInsert = conn
					.prepareStatement("insert into RAW_ITEMS(ID, URL, DATE_TIME, SUBJECT, DESCRIPTION, PICTUREURL, NEXTDAYURL) values (?, ?, ?, ?, ?, ?, ?)");

			int idx = 0;
			for (RawItem item : items) {
				psInsert.setString(1, String.valueOf(idx));
				psInsert.setString(2, item.link);
				psInsert.setString(3, item.dateTime);
				psInsert.setString(4, item.subject);
				psInsert.setString(5, item.description);
				psInsert.setString(6, item.pictureURL);
				psInsert.setString(7, item.nextDayLink);
				psInsert.executeUpdate();
				idx++;
			}
			psInsert.close();
			conn.close();
			System.out.println("Closed connection");

			// ## DATABASE SHUTDOWN SECTION ##
			/***
			 * In embedded mode, an application should shut down Derby. Shutdown
			 * throws the XJ015 exception to confirm success.
			 ***/
			if (driver.equals("org.apache.derby.jdbc.EmbeddedDriver")) {
				boolean gotSQLExc = false;
				try {
					DriverManager.getConnection("jdbc:derby:;shutdown=true");
				} catch (SQLException se) {
					if (se.getSQLState().equals("XJ015")) {
						gotSQLExc = true;
					}
				}
				if (!gotSQLExc) {
					System.out.println("Database did not shut down normally");
				} else {
					System.out.println("Database shut down normally");
				}
			}
		} catch (Throwable e) {
			System.out.println(" . . . exception thrown:");
			errorPrint(e);
		}
	}

	private void workWithDB() {
		String driver = "org.apache.derby.jdbc.ClientDriver";
		String dbName = "sommelier_raw";
		String connectionURL = "jdbc:derby://localhost:1527/" + dbName
				+ ";create=false";
		Connection conn = null;
		PreparedStatement psInsert;

		try {
			Class.forName(driver);
			System.out.println(driver + " loaded. ");
		} catch (java.lang.ClassNotFoundException e) {
			System.err.print("ClassNotFoundException: ");
			System.err.println(e.getMessage());
			System.out
					.println("\n    >>> Please check your CLASSPATH variable   <<<\n");
		}

		try {
			conn = DriverManager.getConnection(connectionURL);
			System.out.println("Connected to database " + dbName);

			psInsert = conn
					.prepareStatement("insert into WISH_LIST(WISH_ITEM) values (?)");
			psInsert.setString(1, "");
			psInsert.executeUpdate();
			psInsert.close();
			conn.close();
			System.out.println("Closed connection");

			// ## DATABASE SHUTDOWN SECTION ##
			/***
			 * In embedded mode, an application should shut down Derby. Shutdown
			 * throws the XJ015 exception to confirm success.
			 ***/
			if (driver.equals("org.apache.derby.jdbc.EmbeddedDriver")) {
				boolean gotSQLExc = false;
				try {
					DriverManager.getConnection("jdbc:derby:;shutdown=true");
				} catch (SQLException se) {
					if (se.getSQLState().equals("XJ015")) {
						gotSQLExc = true;
					}
				}
				if (!gotSQLExc) {
					System.out.println("Database did not shut down normally");
				} else {
					System.out.println("Database shut down normally");
				}
			}
		} catch (Throwable e) {
			System.out.println(" . . . exception thrown:");
			errorPrint(e);
		}
	}

	static void errorPrint(Throwable e) {
		if (e instanceof SQLException)
			SQLExceptionPrint((SQLException) e);
		else {
			System.out.println("A non SQL error occured.");
			e.printStackTrace();
		}
	}

	static void SQLExceptionPrint(SQLException sqle) {
		while (sqle != null) {
			System.out.println("\n---SQLException Caught---\n");
			System.out.println("SQLState:   " + (sqle).getSQLState());
			System.out.println("Severity: " + (sqle).getErrorCode());
			System.out.println("Message:  " + (sqle).getMessage());
			sqle.printStackTrace();
			sqle = sqle.getNextException();
		}
	}
}
